﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using FormAuthentication.Practice.Areas.Customer.Models;
using FormAuthentication.Practice.Areas.Customer.Models.SignIn;
using FormAuthentication.Practice.Models;

namespace FormAuthentication.Practice.Areas.Customer.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var user = UserProvider.GetUser();
            var model = new IndexModel() { CurrentUser = user };

            return View(model);
        }

        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult SignIn(string userName, string password, string returnUrl)
        {
            var serializer = new JavaScriptSerializer();
            var user = new User() { Id = 1, Name = "richie", Username = userName };
            var userData = serializer.Serialize(user);

            var ticket = new FormsAuthenticationTicket(1,
                    userName,
                    DateTime.Now,
                    DateTime.Now.AddDays(30),
                    true,
                    userData,
                    FormsAuthentication.FormsCookiePath);

            var encTicket = FormsAuthentication.Encrypt(ticket);

            Response.Cookies.Add(new HttpCookie(CookiesName.CustomerCookieName, encTicket));

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Home");
        }

        public ActionResult Logout()
        {
            Session.Abandon();

            FormsAuthentication.SignOut();

            var cookie = new HttpCookie(CookiesName.CustomerCookieName);
            cookie.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie);

            return RedirectToAction("Index", "Home");
        }
    }
}